package stud.mpgame.flash.scene;

import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import stud.mpgame.network.UserObject;
import stud.mpgame.flash.assets.ImageManager;
import flash.display.Bitmap;
import flash.Lib;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

class PlayerView extends Sprite {
	
	private var body:Bitmap;
	private var head:Bitmap;
	private var eyes:Bitmap;
	private var leg1:Bitmap;
	private var leg2:Bitmap;
	
	private static var eyeDif = 16;
	private static var difBody = 32;
	private static var EYE_RADIUS:Float = 16;
	private var id:Int;
	
	private var g:GameWorldView;

    public function new(x0:Float, y0:Float, id1:Int, world:GameWorldView){
		super();

		body = ImageManager.getInstance().getUserModel(1);
		head = ImageManager.getInstance().getUserModel(2);
		eyes = ImageManager.getInstance().getUserModel(7); // 6 - cool eye
		leg1 = ImageManager.getInstance().getUserModel(5);
		leg2 = ImageManager.getInstance().getUserModel(5);		
		
		this.id = id1;
		body.x = -difBody;
		body.y = -difBody;
		head.x = -difBody;
		head.y = -difBody;
		leg1.x = -6;
		leg1.y = 20;
		leg2.x = -16;
		leg2.y = 20;
		eyes.x = -eyeDif;
		eyes.y = -eyeDif;
		eyes.scaleY = 1.5;
		eyes.scaleX = 1.5;
		addChild(leg2); 
		addChild(body);
		addChild(head);
		addChild(leg1);
		addChild(eyes);
		this.x = x0;
		this.y = y0;
		this.g = world;
		
		world.addChild(this);
		
		if (this.id == g.getMyId())
			Lib.current.stage.addEventListener(MouseEvent.MOUSE_MOVE, changeEyePos);
	
		trace("add player view");
	}
	
	private function changeEyePos(e:MouseEvent):Void {
		var x:Float = Lib.current.stage.mouseX;
		var y:Float = Lib.current.stage.mouseY;
		
		var p:Point = new Point(x,y);
		var mouseX:Float = this.globalToLocal(p).x;
		var mouseY:Float = this.globalToLocal(p).y;
		var dist = Math.sqrt(mouseX * mouseX + mouseY  * mouseY);
		var sin = mouseY / dist;
		var cos = mouseX / dist;
		eyes.x = EYE_RADIUS * cos - eyeDif;
		eyes.y = EYE_RADIUS * sin - eyeDif;
	}
	
	public function changeCoords(dx:Float, dy:Float, ID:Int) {
		//if (this.id == ID) {
		//	this.x = 400;
		//	this.y = 400;
		//}else {
			this.x += dx; //+ xS);
			this.y += dy; //+ yS);
			changeEyePos(new MouseEvent(MouseEvent.MOUSE_MOVE));
		//	
		//g.addChild(this);
	}
	
	public function setCoords(x:Float, y:Float)	{
		//trace(x + "; " + y);
		
		this.x = x;
		this.y = y;
	}
	
	public function getID():Int {
		return id;
	}	
	
	public function getX():Float{
		return this.x;
	}
	
	public function getY():Float{
		return this.y;
	}
//old
	//public function legsUp() {
	//	leg1.y -= 4;
	//	leg2.y -= 4;
	//}
	
	public function legsMove() {
		//do { leg1.y--; } while (leg1.y <20 ); 
	}
	
	public function legsDown() {
		leg1.scaleX = 0.5;
		leg2.scaleX = 0.5;
	}
}